package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    //新建service对象,用于调用方法
 private final UserService service =new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
    //    获取复选框数据
        String remember = request.getParameter("remember");
        //    调用方法查询用户
        User user = service.login(username, password);
    //    判断用户是否存在
        if (user != null ){
        //    判断是否勾选复选框
            if ("1".equals(remember)){
            //    是，存入cookie
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
            //    设置存活时间，一周
                c_password.setMaxAge(60*60*24*7);
                c_username.setMaxAge(60*60*24*7);
            //    发送cookie信息
                response.addCookie(c_password);
                response.addCookie(c_username);

            }
        //    把用户对象存入session中
            request.getSession().setAttribute("user",user);
        //    登陆成功，重定向selectAllServlet
            response.sendRedirect("selectAllServlet");
        } else {
        //    登陆失败
        //    把错误信息存入请求域
            request.setAttribute("login_msg", "用户名或者密码错误");
        //    跳转login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
